# -*- coding: utf-8 -*-
import email
import imaplib
import re
import ssl
import time
import traceback
from datetime import datetime
from email.header import decode_header
import concurrent.futures
import json
import tempfile
import os
import zipfile
import io

import certifi
import pandas as pd
import streamlit as st
from imapclient import imap_utf7

# 页面配置
st.set_page_config(
    page_title="邮箱IMAP服务权限检查工具",
    page_icon="📧",
    layout="wide",
    initial_sidebar_state="expanded"
)

# 自定义CSS样式
st.markdown("""
<style>
    .header {
        color: #1e88e5;
        border-bottom: 2px solid #1e88e5;
        padding-bottom: 10px;
    }
    .stProgress > div > div > div > div {
        background-color: #1e88e5;
    }
    .stButton>button {
        background-color: #1e88e5 !important;
        color: white !important;
        border: none;
        padding: 10px 24px;
        border-radius: 4px;
        font-weight: 500;
        transition: all 0.3s;
    }
    .stButton>button:hover {
        background-color: #0d47a1 !important;
        transform: scale(1.05);
    }
    .error-box {
        background-color: #ffebee;
        border-left: 4px solid #f44336;
        padding: 10px 15px;
        margin: 15px 0;
        border-radius: 0 4px 4px 0;
    }
    .success-box {
        background-color: #e8f5e9;
        border-left: 4px solid #4caf50;
        padding: 10px 15px;
        margin: 15px 0;
        border-radius: 0 4px 4px 0;
    }
    .info-box {
        background-color: #e3f2fd;
        border-left: 4px solid #2196f3;
        padding: 10px 15px;
        margin: 15px 0;
        border-radius: 0 4px 4px 0;
    }
    .mail-header {
        background-color: #f5f5f5;
        padding: 10px;
        border-radius: 4px;
        margin-bottom: 10px;
    }
    .folder-info {
        background-color: #f8f9fa;
        padding: 8px 12px;
        margin: 5px 0;
        border-radius: 4px;
        border-left: 3px solid #1e88e5;
    }
    .result-card {
        border: 1px solid #e0e0e0;
        border-radius: 8px;
        padding: 15px;
        margin: 10px 0;
        background-color: #fafafa;
    }
    .invalid-uid {
        background-color: #fff3e0;
        border-left: 4px solid #ff9800;
        padding: 10px 15px;
        margin: 10px 0;
        border-radius: 0 4px 4px 0;
    }
    .warning-box {
        background-color: #fff8e1;
        border-left: 4px solid #ffc107;
        padding: 10px 15px;
        margin: 10px 0;
        border-radius: 0 4px 4px 0;
    }
    .batch-download-section {
        background-color: #e8f5e9;
        padding: 15px;
        border-radius: 8px;
        margin: 15px 0;
        border: 1px solid #4caf50;
    }
    .pagination-bottom {
        position: sticky;
        bottom: 0;
        background-color: white;
        padding: 15px 0;
        border-top: 1px solid #e0e0e0;
        margin-top: 20px;
    }
    /* 批量下载区域样式优化 */
    .batch-download-section .stButton button {
        margin: 2px 0;
        font-size: 0.9em;
    }

    /* 筛选区域样式优化 */
    .stMultiSelect [data-baseweb="select"] {
        min-height: 38px;
    }

    .stTextInput input {
        min-height: 38px;
    }

    /* 分页控件样式 */
    .pagination-controls {
        background-color: #f8f9fa;
        padding: 12px;
        border-radius: 8px;
        margin: 10px 0;
    }

    /* 按钮组统一样式 */
    .button-group {
        display: flex;
        gap: 8px;
        align-items: center;
    }

    .button-group .stButton {
        flex: 1;
    }

    /* 紧凑布局优化 */
    .compact-col {
        padding: 0 5px;
    }

    /* 筛选标签样式 */
    .filter-label {
        font-weight: 600;
        margin-bottom: 8px;
        color: #1e88e5;
    }

    /* 统一输入框高度 */
    .stSelectbox, .stMultiselect, .stTextInput {
        min-height: 38px;
    }

    /* 分页按钮样式 */
    .pagination-btn {
        font-size: 0.85em;
        padding: 6px 12px;
    }

    /* 耗时异常样式 */
    .time-warning {
        color: #ff9800;
        font-weight: bold;
    }

    .time-critical {
        color: #f44336;
        font-weight: bold;
    }
</style>
""", unsafe_allow_html=True)

# 应用标题
st.title("📧 邮箱IMAP服务权限与内容检查工具")
st.markdown("""
<div class="info-box">
    功能说明： 此工具用于检查邮箱文件夹权限状态，分析邮件内容获取能力（邮件头/正文），检测异常邮件UID，并监控检查耗时和流量
</div>
""", unsafe_allow_html=True)
st.caption("安全提示： 您的邮箱凭据仅用于本次检查，不会被存储或传输到其他服务器")

# 初始化session state
if 'folder_details' not in st.session_state:
    st.session_state.folder_details = []
if 'results' not in st.session_state:
    st.session_state.results = []
if 'current_check_id' not in st.session_state:
    st.session_state.current_check_id = None
if 'mail_connection' not in st.session_state:
    st.session_state.mail_connection = None
if 'check_config' not in st.session_state:
    st.session_state.check_config = {}
if 'downloaded_emails' not in st.session_state:
    st.session_state.downloaded_emails = {}
if 'uid_stats' not in st.session_state:
    st.session_state.uid_stats = {}
if 'selected_emails' not in st.session_state:
    st.session_state.selected_emails = set()
if 'select_all' not in st.session_state:
    st.session_state.select_all = False
if 'current_page' not in st.session_state:
    st.session_state.current_page = 1
if 'total_check_time' not in st.session_state:
    st.session_state.total_check_time = 0


# 主要功能函数定义
def create_custom_ssl_context():
    context = ssl.create_default_context(cafile=certifi.where())
    context.options |= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1
    context.set_ciphers('DEFAULT:!DH')
    return context


def format_file_size(size_bytes):
    """将字节大小转换为易读的格式 (B, KB, MB, GB)"""
    if size_bytes == 0:
        return "0 B"

    size_names = ["B", "KB", "MB", "GB"]
    i = 0
    while size_bytes >= 1024 and i < len(size_names) - 1:
        size_bytes /= 1024.0
        i += 1

    return f"{size_bytes:.2f} {size_names[i]}"


def check_folder_permissions(cfp_mail, cfp_folder):
    try:
        cfp_status, [_] = cfp_mail.select(cfp_folder, readonly=True)
        if cfp_status != 'OK':
            return "无法访问文件夹", None

        # 检查权限标志
        cfp_status, data = cfp_mail.status(cfp_folder, '(PERMANENTFLAGS)')
        flags_info = data[0].decode('utf-8', 'ignore') if cfp_status == 'OK' else ""

        # 尝试获取邮件数量验证权限
        cfp_status, data = cfp_mail.search(None, 'ALL')
        if cfp_status != 'OK':
            return "只读权限（仅列表）", flags_info

        return "完整权限", flags_info

    except imaplib.IMAP4.error as cfp_e:
        return f"权限检查错误: {str(cfp_e)}", None


def safe_fetch(mail_conn, mail_id, fetch_type):
    """安全的邮件获取函数，处理各种响应格式"""
    try:
        status, data = mail_conn.fetch(mail_id, fetch_type)

        if status != 'OK':
            return None, f"FETCH命令失败: {status}"

        if not data or data == [None]:
            return None, "无数据返回"

        # 处理不同的响应格式
        for item in data:
            if item is None:
                continue

            if isinstance(item, tuple) and len(item) == 2:
                response_part, content = item

                # 检查响应格式
                if content is not None and len(content) > 0:
                    return content, None

            # 处理直接返回内容的情况
            elif isinstance(item, bytes) and len(item) > 100:
                return item, None

        return None, "无法解析响应数据"

    except Exception as e:
        return None, f"获取异常: {str(e)}"


def analyze_email_content_fast(aec_mail, mail_id):
    """快速分析邮件内容 - 只获取头信息"""
    try:
        header_content, error = safe_fetch(aec_mail, mail_id, '(BODY[HEADER])')
        if error:
            return f"无法获取邮件头: {error}", None, None

        if header_content:
            try:
                msg_header = email.message_from_bytes(header_content)
                return "仅邮件头", msg_header, None
            except Exception as e:
                return f"邮件头解析错误: {str(e)}", None, None
        else:
            return "无邮件头数据", None, None

    except Exception as aec_e:
        return f"内容分析错误: {str(aec_e)}", None, None


def analyze_email_content_full(aec_mail, mail_id):
    """完整分析邮件内容"""
    try:
        # 获取邮件头
        header_content, header_error = safe_fetch(aec_mail, mail_id, '(BODY[HEADER])')
        if header_error:
            return f"无法获取邮件头: {header_error}", None, None

        msg_header = None
        if header_content:
            try:
                msg_header = email.message_from_bytes(header_content)
            except Exception as e:
                return f"邮件头解析错误: {str(e)}", None, None

        # 尝试获取正文
        body_content, body_error = safe_fetch(aec_mail, mail_id, '(BODY[TEXT])')
        if body_error:
            return "只能获取邮件头", msg_header, None

        return "完整内容", msg_header, body_content

    except Exception as aec_e:
        return f"内容分析错误: {str(aec_e)}", None, None


def fetch_full_email(ffe_mail, mail_id):
    """获取完整邮件内容"""
    try:
        full_content, error = safe_fetch(ffe_mail, mail_id, '(RFC822)')
        if error or full_content is None:
            return None, error
        return full_content, None

    except Exception as ffe_e:
        return None, f"获取异常: {str(ffe_e)}"


def decode_header_field(header_field):
    if header_field is None:
        return ""

    decoded_parts = decode_header(header_field)
    result = ""

    for part, encoding in decoded_parts:
        if isinstance(part, bytes):
            try:
                result += part.decode(encoding or 'utf-8', 'ignore')
            except:
                try:
                    result += part.decode('gbk', 'ignore')
                except:
                    result += part.decode('latin-1', 'ignore')
        else:
            result += part

    return result


def extract_header_info(header):
    if header is None:
        return {}

    return {
        'subject': decode_header_field(header.get('Subject')),
        'from': decode_header_field(header.get('From')),
        'to': decode_header_field(header.get('To')),
        'date': decode_header_field(header.get('Date')),
        'message_id': decode_header_field(header.get('Message-ID'))
    }


def is_abnormal_uid(uid, existing_uids):
    """检查UID是否异常"""
    if not uid or not isinstance(uid, str):
        return True, "UID为空或非字符串"

    # 检查UID格式
    if not uid.isdigit():
        return True, "非数字UID"

    # 检查UID范围（只在有参考UID时）
    if existing_uids:
        try:
            uid_int = int(uid)
            if existing_uids:  # 确保existing_uids不为空
                min_uid = min(existing_uids)
                max_uid = max(existing_uids)

                # 更宽松的UID范围检查
                if uid_int < min_uid - 10000 or uid_int > max_uid + 10000:
                    return True, f"超出常见范围 ({min_uid}-{max_uid})"
        except Exception as e:
            return True, f"UID比较异常: {str(e)}"

    return False, "正常"


def check_single_mail(mail_conn, mail_id, all_uids, check_mode, is_uid_check=False):
    """检查单封邮件的函数"""
    start_time = time.time()
    try:
        # 安全获取UID
        uid_str = "未知"
        try:
            if is_uid_check:
                # 直接使用UID
                uid_str = mail_id
            else:
                # 使用序列号转换为UID
                idx = int(mail_id) - 1
                if 0 <= idx < len(all_uids):
                    uid_str = str(all_uids[idx])
        except:
            uid_str = "解析失败"

        # 根据检查模式选择分析方法
        if check_mode == "快速检查(仅头信息)":
            content_type, header, body = analyze_email_content_fast(mail_conn, mail_id)
        else:
            content_type, header, body = analyze_email_content_full(mail_conn, mail_id)

        header_info = extract_header_info(header) if header else {}

        # UID检查
        is_abnormal = False
        reason = "正常"

        if uid_str != "解析失败" and uid_str != "未知":
            numeric_uids = [uid for uid in all_uids if isinstance(uid, int)]
            is_abnormal, reason = is_abnormal_uid(uid_str, numeric_uids)

        # 计算检查耗时
        time_cost = time.time() - start_time

        # 计算正文大小
        body_size = len(body) if body else 0
        body_size_formatted = format_file_size(body_size)

        # 判断耗时是否异常
        time_abnormal = False
        time_warning = ""

        # 根据邮件大小和耗时判断是否异常
        if time_cost > 15:  # 超过10秒认为是异常
            time_abnormal = True
            time_warning = f"检查耗时过长: {time_cost:.2f}秒"
        elif body_size > 0 and time_cost > 2 and body_size < 102400:  # 小于100KB但耗时超过2秒
            time_abnormal = True
            time_warning = f"小文件检查耗时异常: {time_cost:.2f}秒"
        elif body_size > 102400 and time_cost > 5 and body_size < 1024000:  # 小于1MB且耗时超过10秒
            time_abnormal = True
            time_warning = f"大文件检查耗时过长: {time_cost:.2f}秒"

        result = {
            "uid": uid_str,
            "status": "正常",
            "content_type": content_type,
            "subject": header_info.get('subject', '无'),
            "from": header_info.get('from', '无'),
            "date": header_info.get('date', '无'),
            "message": "",
            "is_abnormal": is_abnormal,
            "abnormal_reason": reason if is_abnormal else "",
            "mail_id": str(mail_id),
            "uid_type": "UID" if is_uid_check else "序列号",
            "time_cost": time_cost,
            "body_size": body_size,
            "body_size_formatted": body_size_formatted,
            "time_abnormal": time_abnormal,
            "time_warning": time_warning
        }

        if "错误" in content_type or "无法获取" in content_type:
            result["status"] = "错误"
            result["message"] = content_type
        elif content_type == "只能获取邮件头":
            result["status"] = "受限"
            result["message"] = "只能获取邮件头"
        elif is_abnormal:
            result["status"] = "异常"
            result["message"] = f"UID异常: {reason}"
        elif time_abnormal:
            result["status"] = "异常"
            result["message"] = time_warning
            result["abnormal_reason"] = time_warning
        else:
            result["message"] = f"正文大小: {body_size_formatted}, 检查耗时: {time_cost:.2f}秒"

        return result

    except Exception as e:
        time_cost = time.time() - start_time
        return {
            "uid": "未知",
            "status": "错误",
            "content_type": f"检查失败: {str(e)}",
            "subject": "无",
            "from": "无",
            "date": "无",
            "message": f"处理失败: {str(e)}",
            "is_abnormal": True,
            "abnormal_reason": "处理异常",
            "mail_id": str(mail_id),
            "uid_type": "UID" if is_uid_check else "序列号",
            "time_cost": time_cost,
            "body_size": 0,
            "body_size_formatted": "0 B",
            "time_abnormal": True,
            "time_warning": f"处理异常: {time_cost:.2f}秒"
        }


def run_check(rc_server, rc_port, rc_username, rc_password, rc_folder, rc_start_idx, rc_end_idx, check_mode,
              include_invalid_uids):
    rc_results = []
    total_check_time = 0

    # 生成检查ID用于状态管理
    check_id = f"{rc_username}_{rc_folder}_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
    st.session_state.current_check_id = check_id

    try:
        progress_bar = st.progress(0)
        status_text = st.empty()

        # 连接服务器
        if rc_port == 993:
            status_text.info(f"正在连接到服务器 {rc_server}:{rc_port} (SSL)...")
            rc_custom_ssl_context = create_custom_ssl_context()
            rc_mail = imaplib.IMAP4_SSL(rc_server, rc_port, ssl_context=rc_custom_ssl_context)
        elif rc_port == 143:
            status_text.info(f"正在连接到服务器 {rc_server}:{rc_port} (非SSL)...")
            rc_mail = imaplib.IMAP4(rc_server, rc_port)
        elif rc_port == 587:
            status_text.info(f"正在连接到服务器 {rc_server}:{rc_port} (SSL)...")
            rc_custom_ssl_context = create_custom_ssl_context()
            rc_mail = imaplib.IMAP4_SSL(rc_server, rc_port, ssl_context=rc_custom_ssl_context)
        else:
            raise ValueError("不支持的端口号")

        rc_mail.login(rc_username, rc_password)
        status_text.success(f"登录成功: {rc_username}")
        time.sleep(0.5)
        progress_bar.progress(10)

        encoded_folder = imap_utf7.encode(rc_folder)
        status_text.info(f"检查文件夹: {rc_folder}")
        time.sleep(0.5)
        progress_bar.progress(20)

        # 检查文件夹权限
        permissions, flags_info = check_folder_permissions(rc_mail, encoded_folder)
        status_text.info(f"文件夹权限: {permissions}")
        if flags_info:
            st.info(f"权限标志: {flags_info}")
        time.sleep(0.5)
        progress_bar.progress(30)

        # 选择文件夹
        rc_status, _ = rc_mail.select(encoded_folder)
        if rc_status != 'OK':
            status_text.error(f"错误: 无法选择文件夹 '{rc_folder}'")
            return rc_results

        progress_bar.progress(40)

        # 使用多种方式搜索邮件，确保获取所有邮件
        status_text.info("正在搜索邮件...")

        # 方法1: 普通搜索
        rc_status, data = rc_mail.search(None, 'ALL')
        mail_ids = data[0].split() if rc_status == 'OK' and data[0] else []

        # 方法2: UID搜索
        rc_status_uid, data_uid = rc_mail.uid('SEARCH', 'ALL')
        uid_data = data_uid[0].split() if rc_status_uid == 'OK' and data_uid[0] else []

        # 统计信息
        total_regular = len(mail_ids)
        total_uid = len(uid_data)

        status_text.info(f"搜索完成 - 普通搜索: {total_regular} 封, UID搜索: {total_uid} 封")

        # 处理UID数据
        valid_uids = []
        invalid_uids = []

        for uid in uid_data:
            try:
                uid_str = uid.decode('utf-8')
                if uid_str.isdigit():
                    valid_uids.append(int(uid_str))
                else:
                    invalid_uids.append(uid_str)
            except:
                invalid_uids.append(str(uid))

        valid_uids.sort()

        # 使用UID搜索的结果作为主要参考（通常更准确）
        if uid_data:
            all_uids = valid_uids + invalid_uids
            total_mails = len(all_uids)
            status_text.info(
                f"使用UID搜索结果: {total_mails} 封邮件 (有效UID: {len(valid_uids)}, 无效UID: {len(invalid_uids)})")
        else:
            all_uids = [int(uid) for uid in mail_ids]
            total_mails = len(all_uids)
            status_text.info(f"使用普通搜索结果: {total_mails} 封邮件")
            invalid_uids = []

        # 保存UID统计信息
        st.session_state.uid_stats = {
            'total_regular': total_regular,
            'total_uid': total_uid,
            'valid_uids': len(valid_uids),
            'invalid_uids': len(invalid_uids),
            'total_mails': total_mails
        }

        if not all_uids:
            status_text.info("文件夹中没有邮件")
            return rc_results

        progress_bar.progress(60)

        # 确定检查范围
        if rc_end_idx == 0 or rc_end_idx > len(all_uids):
            rc_end_idx = len(all_uids)

        rc_start_idx = max(0, rc_start_idx)
        rc_end_idx = min(len(all_uids), rc_end_idx)

        # 对于快速检查，使用随机采样而不是连续范围
        if check_mode == "快速检查(仅头信息)":
            import random
            sample_indices = random.sample(range(len(all_uids)), min(rc_end_idx, len(all_uids)))
            check_indices = sample_indices
        else:
            check_indices = range(rc_start_idx, rc_end_idx)

        total = len(check_indices)

        status_text.info(f"检查邮件数量: {total} (模式: {check_mode})")
        time.sleep(0.5)
        progress_bar.progress(70)

        abnormal_count = 0
        invalid_uid_count = 0
        time_abnormal_count = 0

        # 顺序检查邮件
        for i, idx in enumerate(check_indices):
            if idx < len(valid_uids):
                # 检查有效UID邮件
                mail_seq_num = idx + 1  # IMAP序列号从1开始
                result = check_single_mail(rc_mail, str(mail_seq_num), all_uids, check_mode, False)
            else:
                # 检查无效UID邮件（使用UID直接获取）
                invalid_idx = idx - len(valid_uids)
                if invalid_idx < len(invalid_uids) and include_invalid_uids:
                    invalid_uid = invalid_uids[invalid_idx]
                    # 使用UID FETCH命令检查无效UID邮件
                    try:
                        rc_status, data = rc_mail.uid('FETCH', invalid_uid, '(BODY[HEADER])')
                        if rc_status == 'OK' and data and data[0]:
                            result = {
                                "uid": invalid_uid,
                                "status": "异常",
                                "content_type": "无效UID邮件",
                                "subject": "无效UID邮件",
                                "from": "未知",
                                "date": "未知",
                                "message": "此邮件UID格式异常",
                                "is_abnormal": True,
                                "abnormal_reason": "非数字UID",
                                "mail_id": invalid_uid,
                                "uid_type": "无效UID",
                                "time_cost": 0,
                                "body_size": 0,
                                "body_size_formatted": "0 B",
                                "time_abnormal": False,
                                "time_warning": ""
                            }
                            invalid_uid_count += 1
                        else:
                            result = {
                                "uid": invalid_uid,
                                "status": "错误",
                                "content_type": "无法获取",
                                "subject": "无",
                                "from": "无",
                                "date": "无",
                                "message": "无法获取无效UID邮件内容",
                                "is_abnormal": True,
                                "abnormal_reason": "无效UID无法访问",
                                "mail_id": invalid_uid,
                                "uid_type": "无效UID",
                                "time_cost": 0,
                                "body_size": 0,
                                "body_size_formatted": "0 B",
                                "time_abnormal": False,
                                "time_warning": ""
                            }
                    except Exception as e:
                        result = {
                            "uid": invalid_uid,
                            "status": "错误",
                            "content_type": f"检查异常: {str(e)}",
                            "subject": "无",
                            "from": "无",
                            "date": "无",
                            "message": f"无效UID检查失败: {str(e)}",
                            "is_abnormal": True,
                            "abnormal_reason": "无效UID检查异常",
                            "mail_id": invalid_uid,
                            "uid_type": "无效UID",
                            "time_cost": 0,
                            "body_size": 0,
                            "body_size_formatted": "0 B",
                            "time_abnormal": False,
                            "time_warning": ""
                        }
                else:
                    continue

            rc_results.append(result)
            total_check_time += result.get("time_cost", 0)

            if result["status"] != "正常":
                abnormal_count += 1

            if result.get("time_abnormal", False):
                time_abnormal_count += 1

            # 更新进度
            completed = i + 1
            progress = 70 + int(30 * completed / total)
            progress_bar.progress(progress)

            # 实时显示结果（每10封邮件更新一次，避免性能问题）
            if completed % 10 == 0 or completed == total:
                status_text.info(f"已检查 {completed}/{total} 封邮件... (耗时异常: {time_abnormal_count} 封)")

        progress_bar.progress(100)

        # 保存总耗时
        st.session_state.total_check_time = total_check_time

        # 保存连接配置用于后续下载
        st.session_state.check_config = {
            'server': rc_server,
            'port': rc_port,
            'username': rc_username,
            'password': rc_password,
            'folder': rc_folder
        }

        # 关闭连接
        rc_mail.logout()

        return rc_results

    except imaplib.IMAP4.error as rc_e:
        st.error(f"IMAP操作失败: {str(rc_e)}")
        return rc_results
    except Exception as rc_e:
        st.error(f"发生错误: {str(rc_e)}")
        st.text(traceback.format_exc())
        return rc_results


def download_single_email(uid, mail_id, uid_type):
    """下载单封邮件"""
    try:
        config = st.session_state.check_config
        if not config:
            st.error("检查配置丢失，请重新执行检查")
            return None

        # 重新连接服务器
        if config['port'] == 993:
            custom_ssl_context = create_custom_ssl_context()
            mail = imaplib.IMAP4_SSL(config['server'], config['port'], ssl_context=custom_ssl_context)
        elif config['port'] == 143:
            mail = imaplib.IMAP4(config['server'], config['port'])
        elif config['port'] == 587:
            custom_ssl_context = create_custom_ssl_context()
            mail = imaplib.IMAP4_SSL(config['server'], config['port'], ssl_context=custom_ssl_context)
        else:
            st.error("不支持的端口号")
            return None

        mail.login(config['username'], config['password'])

        # 选择文件夹
        encoded_folder = imap_utf7.encode(config['folder'])
        mail.select(encoded_folder)

        # 根据UID类型选择获取方式
        if uid_type == "无效UID":
            # 使用UID FETCH获取无效UID邮件
            status, data = mail.uid('FETCH', mail_id, '(RFC822)')
            if status == 'OK' and data and data[0]:
                if isinstance(data[0], tuple) and len(data[0]) == 2:
                    full_email = data[0][1]
                else:
                    full_email = None
            else:
                full_email = None
        else:
            # 正常获取
            full_email, error = fetch_full_email(mail, mail_id)

        # 关闭连接
        mail.logout()

        if not full_email:
            st.error("下载失败: 无法获取邮件内容")
            return None

        return full_email

    except Exception as e:
        st.error(f"下载过程中发生错误: {str(e)}")
        return None


def download_batch_emails(selected_results):
    """批量下载选中的邮件"""
    if not selected_results:
        st.error("请先选择要下载的邮件")
        return None

    try:
        config = st.session_state.check_config
        if not config:
            st.error("检查配置丢失，请重新执行检查")
            return None

        # 创建内存中的ZIP文件
        zip_buffer = io.BytesIO()
        with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
            downloaded_count = 0

            # 重新连接服务器
            if config['port'] == 993:
                custom_ssl_context = create_custom_ssl_context()
                mail = imaplib.IMAP4_SSL(config['server'], config['port'], ssl_context=custom_ssl_context)
            elif config['port'] == 143:
                mail = imaplib.IMAP4(config['server'], config['port'])
            elif config['port'] == 587:
                custom_ssl_context = create_custom_ssl_context()
                mail = imaplib.IMAP4_SSL(config['server'], config['port'], ssl_context=custom_ssl_context)
            else:
                st.error("不支持的端口号")
                return None

            mail.login(config['username'], config['password'])

            # 选择文件夹
            encoded_folder = imap_utf7.encode(config['folder'])
            mail.select(encoded_folder)

            progress_bar = st.progress(0)
            status_text = st.empty()

            total = len(selected_results)

            for i, result in enumerate(selected_results):
                status_text.info(f"正在下载第 {i + 1}/{total} 封邮件...")

                # 下载单封邮件
                email_content = download_single_email(result['uid'], result['mail_id'],
                                                      result.get('uid_type', '序列号'))
                if email_content:
                    # 生成文件名
                    subject = result['subject'][:50] if result['subject'] and result['subject'] != '无' else '无主题'
                    filename = f"{result['uid']}_{subject}.eml".replace('/', '_').replace('\\', '_')

                    # 添加到ZIP文件
                    zip_file.writestr(filename, email_content)
                    downloaded_count += 1

                # 更新进度
                progress = int((i + 1) / total * 100)
                progress_bar.progress(progress)

            # 关闭连接
            mail.logout()

        if downloaded_count > 0:
            status_text.success(f"成功下载 {downloaded_count} 封邮件")
            zip_buffer.seek(0)
            return zip_buffer
        else:
            status_text.error("没有成功下载任何邮件")
            return None

    except Exception as e:
        st.error(f"批量下载过程中发生错误: {str(e)}")
        return None


def get_folder_statistics(mail, folder_name):
    """获取文件夹的详细统计信息"""
    try:
        encoded_folder = imap_utf7.encode(folder_name)
        mail.select(encoded_folder, readonly=True)

        # 方法1: 普通搜索 - 获取所有邮件的序列号
        status_all, data_all = mail.search(None, 'ALL')
        regular_ids = data_all[0].split() if status_all == 'OK' and data_all[0] else []
        regular_count = len(regular_ids)

        # 方法2: UID搜索 - 获取所有邮件的UID
        status_uid, data_uid = mail.uid('SEARCH', 'ALL')
        uid_data = data_uid[0].split() if status_uid == 'OK' and data_uid[0] else []
        uid_count = len(uid_data)

        # 分析UID数据
        valid_uids = []
        invalid_uids = []
        uid_details = []

        for uid_bytes in uid_data:
            try:
                uid_str = uid_bytes.decode('utf-8', errors='ignore')

                # 检查UID格式
                if uid_str.isdigit():
                    uid_int = int(uid_str)
                    valid_uids.append(uid_int)
                    uid_details.append({
                        'uid': uid_str,
                        'type': '有效UID',
                        'status': '正常'
                    })
                else:
                    invalid_uids.append(uid_str)
                    uid_details.append({
                        'uid': uid_str,
                        'type': '无效UID',
                        'status': '格式异常'
                    })
            except Exception as e:
                invalid_uid = str(uid_bytes)[:50]  # 限制长度
                invalid_uids.append(invalid_uid)
                uid_details.append({
                    'uid': invalid_uid,
                    'type': '无效UID',
                    'status': f'解码异常: {str(e)}'
                })

        # 计算总数 - 使用最大的计数方法
        total_count = max(regular_count, uid_count, len(uid_details))

        # 获取UID范围
        uid_range = "无邮件"
        if valid_uids:
            min_uid = min(valid_uids)
            max_uid = max(valid_uids)
            uid_range = f"{min_uid}-{max_uid}"

        # 检查序列号与UID数量差异
        seq_uid_diff = abs(regular_count - uid_count)
        has_discrepancy = seq_uid_diff > 0

        return {
            'name': folder_name,
            'total_count': total_count,
            'regular_count': regular_count,
            'uid_count': uid_count,
            'valid_uids': len(valid_uids),
            'invalid_uids': len(invalid_uids),
            'uid_range': uid_range,
            'invalid_uid_list': invalid_uids[:20],  # 只保留前20个作为示例
            'uid_details': uid_details[:100],  # 只保留前100个UID详情
            'has_discrepancy': has_discrepancy,
            'discrepancy_count': seq_uid_diff,
            'regular_ids_count': len(regular_ids),
            'uid_data_count': len(uid_data)
        }

    except Exception as e:
        return {
            'name': folder_name,
            'total_count': 0,
            'regular_count': 0,
            'uid_count': 0,
            'valid_uids': 0,
            'invalid_uids': 0,
            'uid_range': f"错误: {str(e)}",
            'invalid_uid_list': [],
            'uid_details': [],
            'has_discrepancy': False,
            'discrepancy_count': 0,
            'regular_ids_count': 0,
            'uid_data_count': 0
        }


# 侧边栏 - 邮箱配置（简化版）
with st.sidebar:
    st.header("📧 邮箱配置")

    server = st.text_input("IMAP服务器", "")
    port_options = [143, 993, 587]
    port = st.selectbox("端口号", options=port_options, index=1)
    username = st.text_input("邮箱用户名", "")
    password = st.text_input("邮箱密码", "", type="password")

    st.divider()
    st.header("🔧 快速操作")

    if st.button("🚀 获取文件夹列表", use_container_width=True):
        st.session_state.show_folder_stats = True
    if st.button("🗑️ 清除所有结果", use_container_width=True):
        st.session_state.folder_details = []
        st.session_state.results = []
        st.session_state.selected_emails = set()
        st.session_state.select_all = False
        st.session_state.current_page = 1
        st.session_state.total_check_time = 0
        st.rerun()

    st.divider()
    st.caption("💡 使用提示：")
    st.caption("1. 先配置邮箱信息")
    st.caption("2. 点击获取文件夹列表")
    st.caption("3. 在右侧选择文件夹并检查")

# 主区域 - 文件夹统计和检查功能
if st.session_state.get('show_folder_stats', False):
    if not server or not username or not password:
        st.error("请先填写邮箱配置信息")
    else:
        try:
            with st.spinner("正在连接服务器并获取文件夹列表..."):
                if port == 993:
                    custom_ssl_context = create_custom_ssl_context()
                    mail = imaplib.IMAP4_SSL(server, port, ssl_context=custom_ssl_context)
                elif port == 143:
                    mail = imaplib.IMAP4(server, port)
                elif port == 587:
                    custom_ssl_context = create_custom_ssl_context()
                    mail = imaplib.IMAP4_SSL(server, port, ssl_context=custom_ssl_context)
                else:
                    raise ValueError("不支持的端口号")

                mail.login(username, password)
                st.success(f"登录成功: {username}")

                status, folders = mail.list()
                if status == 'OK':
                    folder_details = []

                    # 获取邮箱文件夹列表
                    folder_list_org = mail.list()
                    for i in folder_list_org[1]:
                        try:
                            # 解码文件夹名称
                            parts = imap_utf7.decode(i).split('"')
                            if len(parts) > 3:
                                folder_name = imap_utf7.decode(i).split('/" ')[-1].replace('"', '')
                            else:
                                folder_name = parts[-1].replace('\\', '').strip()

                            # 获取文件夹统计信息
                            folder_stats = get_folder_statistics(mail, folder_name)
                            folder_details.append(folder_stats)

                        except Exception as e:
                            st.warning(f"处理文件夹 {folder_name} 时出错: {str(e)}")
                            continue

                    st.session_state.folder_details = folder_details
                    st.success(f"✅ 成功获取 {len(folder_details)} 个文件夹的详细统计信息")

                else:
                    st.error("无法获取文件夹列表")

                mail.logout()

        except imaplib.IMAP4.error as e:
            st.error(f"IMAP操作失败: {str(e)}")
        except Exception as e:
            st.error(f"发生错误: {str(e)}")
            st.text(traceback.format_exc())

# 显示文件夹统计信息
if st.session_state.folder_details:
    st.header("📊 文件夹统计信息")

    # 总体统计
    total_folders = len(st.session_state.folder_details)
    total_emails = sum(f['total_count'] for f in st.session_state.folder_details)
    total_invalid = sum(f['invalid_uids'] for f in st.session_state.folder_details)
    folders_with_issues = sum(
        1 for f in st.session_state.folder_details if f['invalid_uids'] > 0 or f['has_discrepancy'])

    col1, col2, col3, col4 = st.columns(4)
    col1.metric("文件夹数量", total_folders)
    col2.metric("总邮件数", total_emails)
    col3.metric("无效UID总数", total_invalid)
    col4.metric("异常文件夹", folders_with_issues)

    # 文件夹选择
    st.header("🔍 选择检查文件夹")

    col1, col2 = st.columns([2, 1])
    with col1:
        folder_options = [f"{fd['name']} ({fd['total_count']} 封邮件)" for fd in st.session_state.folder_details]
        selected_folder = st.selectbox("选择邮箱文件夹", options=folder_options, key="folder_select")
        folder = selected_folder.split(" (")[0]  # 提取纯文件夹名称
    with col2:
        # 显示选中文件夹的详细信息
        selected_folder_stats = next((f for f in st.session_state.folder_details if f['name'] == folder), None)
        if selected_folder_stats:
            st.metric("选中文件夹邮件数", selected_folder_stats['total_count'])

    # 检查设置
    st.header("⚙️ 检查设置")

    col1, col2 = st.columns(2)
    with col1:
        # 智能检查选项
        check_mode = st.radio("检查模式",
                              ["快速检查(仅头信息)", "完整检查(头信息+采样内容)", "深度检查(全部内容)"],
                              help="快速检查仅验证权限和UID，完整检查采样部分邮件内容，深度检查获取所有邮件完整内容")

        # 根据模式调整检查范围
        if check_mode == "快速检查(仅头信息)":
            sample_size = st.slider("采样邮件数量", 10, 1000, 100,
                                    help="快速模式下检查的邮件数量")
            start_idx = 0
            end_idx = sample_size
        elif check_mode == "完整检查(头信息+采样内容)":
            sample_size = st.slider("采样邮件数量", 10, 500, 50)
            start_idx = 0
            end_idx = sample_size
        else:  # 深度检查
            start_idx = st.number_input("起始邮件序号", min_value=0, value=0)
            end_idx = st.number_input("结束邮件序号", min_value=0, value=100,
                                      help="设置为0表示检查所有邮件")

    with col2:
        # 包含无效UID选项
        include_invalid_uids = st.checkbox("包含无效UID检查", value=True,
                                           help="检查非数字UID等异常格式的邮件")

        # 批量下载选项
        st.subheader("📦 批量下载设置")
        auto_download = st.checkbox("启用批量下载选择", value=True,
                                    help="在检查结果中显示批量下载选项")
        st.session_state.auto_download = auto_download

    # 开始检查按钮
    if st.button("🚀 开始检查", type="primary", use_container_width=True):
        if not folder:
            st.error("请选择要检查的文件夹")
        else:
            st.session_state.current_config = {
                'server': server,
                'port': port,
                'username': username,
                'folder': folder,
                'check_mode': check_mode
            }

            with st.spinner("正在检查邮箱权限和邮件内容..."):
                results = run_check(server, port, username, password, folder, start_idx, end_idx, check_mode,
                                    include_invalid_uids)
                st.session_state.results = results
                st.session_state.last_check_time = datetime.now()
                st.session_state.selected_emails = set()  # 重置选择状态
                st.session_state.select_all = False
                st.session_state.current_page = 1
                st.rerun()

# 显示检查结果
if "results" in st.session_state and st.session_state.results:
    results = st.session_state.results

    # 显示UID统计信息
    if 'uid_stats' in st.session_state and st.session_state.uid_stats:
        stats = st.session_state.uid_stats
        st.subheader("📊 UID统计信息")
        col1, col2, col3, col4 = st.columns(4)
        col1.metric("普通搜索", stats['total_regular'])
        col2.metric("UID搜索", stats['total_uid'])
        col3.metric("有效UID", stats['valid_uids'])
        col4.metric("无效UID", stats['invalid_uids'])

    # 显示检查摘要
    st.subheader("检查摘要")
    total = len(results)
    abnormal_count = sum(1 for r in results if r["status"] != "正常")
    invalid_uid_results = [r for r in results if r.get("uid_type") == "无效UID"]
    time_abnormal_results = [r for r in results if r.get("time_abnormal", False)]

    # 计算总数据量
    total_data_size = sum(r.get("body_size", 0) for r in results)
    total_data_size_formatted = format_file_size(total_data_size)

    # 计算平均耗时
    avg_time = st.session_state.total_check_time / total if total > 0 else 0

    col1, col2, col3, col4, col5, col6 = st.columns(6)
    col1.metric("检查邮件数", total)
    col2.metric("正常邮件", total - abnormal_count, f"{(total - abnormal_count) / total * 100:.1f}%")
    col3.metric("异常邮件", abnormal_count, f"{abnormal_count / total * 100:.1f}%")
    col4.metric("无效UID邮件", len(invalid_uid_results))
    col5.metric("耗时异常", len(time_abnormal_results))
    col6.metric("总数据量", total_data_size_formatted)

    # 显示耗时统计
    st.subheader("⏱️ 耗时统计")
    time_col1, time_col2, time_col3, time_col4 = st.columns(4)
    time_col1.metric("总检查耗时", f"{st.session_state.total_check_time:.2f}秒")
    time_col2.metric("平均每封邮件耗时", f"{avg_time:.2f}秒")

    # 找到耗时最长的邮件
    if results:
        max_time_mail = max(results, key=lambda x: x.get("time_cost", 0))
        time_col3.metric("单封最长耗时", f"{max_time_mail.get('time_cost', 0):.2f}秒")
        time_col4.metric("最长耗时邮件UID", max_time_mail.get("uid", "未知"))

    # 批量下载功能
    if st.session_state.get('auto_download', True):
        st.markdown('<div class="batch-download-section">', unsafe_allow_html=True)
        st.subheader("📦 批量下载")

        # 使用更合理的列布局
        col1, col2, col3, col4 = st.columns([1.2, 1.2, 1.5, 2])

        with col1:
            # 全选按钮 - 统一宽度
            if st.button("✅ 全选", key="select_all_btn", use_container_width=True):
                st.session_state.select_all = True
                st.session_state.selected_emails = set(range(len(results)))

        with col2:
            # 取消全选按钮 - 统一宽度
            if st.button("❌ 取消全选", key="deselect_all_btn", use_container_width=True):
                st.session_state.select_all = False
                st.session_state.selected_emails = set()

        with col3:
            # 已选择邮件计数 - 居中显示
            selected_count = len(st.session_state.selected_emails)
            st.metric("已选择邮件", selected_count)

        with col4:
            # 下载按钮 - 根据选择状态动态显示
            if selected_count > 0:
                if st.button(f"📥 下载选中邮件 ({selected_count}封)",
                             type="primary", use_container_width=True):
                    selected_results = [results[i] for i in st.session_state.selected_emails]
                    zip_buffer = download_batch_emails(selected_results)
                    if zip_buffer:
                        st.download_button(
                            label="⬇️ 下载ZIP文件",
                            data=zip_buffer.getvalue(),
                            file_name=f"batch_emails_{datetime.now().strftime('%Y%m%d_%H%M%S')}.zip",
                            mime="application/zip",
                            use_container_width=True
                        )
            else:
                st.button("📥 下载选中邮件", disabled=True, use_container_width=True)

        st.markdown('</div>', unsafe_allow_html=True)

    # 显示详细结果
    st.subheader("🔍 详细结果")

    # 结果筛选 - 使用更紧凑的布局
    st.markdown("**筛选条件:**")
    filter_col1, filter_col2, filter_col3 = st.columns([2, 2, 3])

    with filter_col1:
        status_options = list(set(r["status"] for r in results))
        filter_status = st.multiselect(
            "状态筛选",
            options=status_options,
            default=status_options,
            key="filter_status_top"
        )

    with filter_col2:
        uid_type_options = list(set(r.get("uid_type", "序列号") for r in results))
        filter_uid_type = st.multiselect(
            "UID类型",
            options=uid_type_options,
            default=uid_type_options,
            key="filter_uid_type_top"
        )

    with filter_col3:
        search_term = st.text_input(
            "搜索主题/发件人",
            placeholder="输入关键词搜索...",
            key="search_top"
        )

    # 过滤结果
    filtered_results = [r for r in results if
                        r["status"] in filter_status and r.get("uid_type", "序列号") in filter_uid_type]
    if search_term:
        filtered_results = [r for r in filtered_results if
                            search_term.lower() in r.get('subject', '').lower() or
                            search_term.lower() in r.get('from', '').lower()]

    # 分页显示
    page_size = 20
    total_pages = max(1, (len(filtered_results) + page_size - 1) // page_size)

    # 确保页码在有效范围内
    if st.session_state.current_page > total_pages:
        st.session_state.current_page = total_pages
    if st.session_state.current_page < 1:
        st.session_state.current_page = 1

    # 分页控制 - 更紧凑的布局
    st.markdown("---")
    page_col1, page_col2, page_col3 = st.columns([1, 2, 1])

    with page_col1:
        st.markdown(f"**第 {st.session_state.current_page} 页，共 {total_pages} 页**")
        st.markdown(f"**显示 {len(filtered_results)} 条结果**")

    with page_col2:
        # 页码输入居中显示
        new_page = st.number_input(
            "跳转到页码",
            min_value=1,
            max_value=total_pages,
            value=st.session_state.current_page,
            key="page_top",
            label_visibility="collapsed"
        )
        if new_page != st.session_state.current_page:
            st.session_state.current_page = new_page
            st.rerun()

    with page_col3:
        # 添加快速导航按钮
        nav_col1, nav_col2 = st.columns(2)
        with nav_col1:
            if st.button("◀ 上一页", key="prev_top", use_container_width=True):
                if st.session_state.current_page > 1:
                    st.session_state.current_page -= 1
                    st.rerun()
        with nav_col2:
            if st.button("下一页 ▶", key="next_top", use_container_width=True):
                if st.session_state.current_page < total_pages:
                    st.session_state.current_page += 1
                    st.rerun()

    start_idx = (st.session_state.current_page - 1) * page_size
    end_idx = min(start_idx + page_size, len(filtered_results))

    current_page_results = filtered_results[start_idx:end_idx]

    # 显示当前页结果
    for idx, result in enumerate(current_page_results):
        global_idx = start_idx + idx

        with st.container():
            if result.get("uid_type") == "无效UID":
                st.markdown('<div class="invalid-uid">', unsafe_allow_html=True)
            else:
                st.markdown('<div class="result-card">', unsafe_allow_html=True)

            # 选择复选框
            col_check, col_content = st.columns([1, 15])
            with col_check:
                is_selected = st.checkbox(
                    "",
                    value=global_idx in st.session_state.selected_emails,
                    key=f"select_{result['uid']}_{result['mail_id']}"
                )
                if is_selected:
                    st.session_state.selected_emails.add(global_idx)
                else:
                    st.session_state.selected_emails.discard(global_idx)

            with col_content:
                # 根据状态显示不同的颜色和图标
                status_color = "🟢" if result["status"] == "正常" else "🔴" if result["status"] == "错误" else "🟡"
                time_warning_class = ""
                if result.get("time_abnormal", False):
                    if result.get("time_cost", 0) > 15:
                        time_warning_class = "time-critical"
                    else:
                        time_warning_class = "time-warning"

                st.markdown(f"{status_color} **邮件 UID {result['uid']} - 状态: {result['status']}**")

                col1, col2 = st.columns([3, 1])

                with col1:
                    st.markdown(f"**UID类型:** {result.get('uid_type', '序列号')}")
                    st.markdown(f"**主题:** {result['subject']}")
                    st.markdown(f"**发件人:** {result['from']}")
                    st.markdown(f"**日期:** {result['date']}")
                    st.markdown(f"**内容类型:** {result['content_type']}")
                    if result['message']:
                        st.markdown(f"**详情:** {result['message']}")
                    if result['is_abnormal'] and result['abnormal_reason']:
                        st.markdown(f"**异常原因:** {result['abnormal_reason']}")

                    # 显示耗时和大小信息
                    time_display = f"**检查耗时:** <span class='{time_warning_class}'>{result.get('time_cost', 0):.2f}秒</span>" if time_warning_class else f"**检查耗时:** {result.get('time_cost', 0):.2f}秒"
                    st.markdown(time_display, unsafe_allow_html=True)
                    st.markdown(f"**正文大小:** {result.get('body_size_formatted', '0 B')}")

                with col2:
                    # 下载按钮
                    download_key = f"download_{result['uid']}_{result['mail_id']}"
                    if st.button("📥 获取完整邮件", key=download_key, use_container_width=True):
                        with st.spinner("正在获取邮件..."):
                            email_content = download_single_email(result['uid'], result['mail_id'],
                                                                  result.get('uid_type', '序列号'))
                            if email_content:
                                # 使用download_button直接提供下载
                                filename = f"email_{result['uid']}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.eml"

                                st.download_button(
                                    label="⬇️ 下载EML文件",
                                    data=email_content,
                                    file_name=filename,
                                    mime="message/rfc822",
                                    key=f"dl_{result['uid']}_{result['mail_id']}",
                                    use_container_width=True
                                )
                            else:
                                st.error("获取邮件失败")

            st.markdown('</div>', unsafe_allow_html=True)

    # 底部页码选择
    st.markdown('<div class="pagination-bottom">', unsafe_allow_html=True)
    st.markdown("---")
    page_col1_b, page_col2_b, page_col3_b = st.columns([1, 2, 1])

    with page_col1_b:
        st.markdown(f"**第 {st.session_state.current_page} 页，共 {total_pages} 页**")

    with page_col2_b:
        new_page_bottom = st.number_input("跳转到页码", min_value=1, max_value=total_pages,
                                          value=st.session_state.current_page,
                                          key="page_bottom", label_visibility="collapsed")
        if new_page_bottom != st.session_state.current_page:
            st.session_state.current_page = new_page_bottom
            st.rerun()

    with page_col3_b:
        nav_col1_b, nav_col2_b = st.columns(2)
        with nav_col1_b:
            if st.button("◀ 上一页", key="prev_bottom", use_container_width=True) and st.session_state.current_page > 1:
                st.session_state.current_page -= 1
                st.rerun()
        with nav_col2_b:
            if st.button("下一页 ▶", key="next_bottom",
                         use_container_width=True) and st.session_state.current_page < total_pages:
                st.session_state.current_page += 1
                st.rerun()

    st.markdown('</div>', unsafe_allow_html=True)

# 结果显示和导出区域
if "results" in st.session_state and st.session_state.results:
    st.sidebar.divider()
    st.sidebar.subheader("📤 导出结果")

    col1, col2 = st.sidebar.columns(2)

    with col1:
        # 导出CSV
        csv_data = pd.DataFrame(st.session_state.results).to_csv(index=False).encode('utf-8')
        st.download_button(
            label="📊 导出CSV",
            data=csv_data,
            file_name=f"mail_check_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
            mime="text/csv",
            use_container_width=True
        )

    with col2:
        # 导出JSON
        json_data = json.dumps(st.session_state.results, ensure_ascii=False, indent=2)
        st.download_button(
            label="📋 导出JSON",
            data=json_data,
            file_name=f"mail_check_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json",
            mime="application/json",
            use_container_width=True
        )

# 显示历史检查信息
if 'current_config' in st.session_state:
    with st.expander("📋 当前检查配置"):
        config = st.session_state.current_config
        st.write(f"**服务器:** {config['server']}:{config['port']}")
        st.write(f"**用户名:** {config['username']}")
        st.write(f"**文件夹:** {config['folder']}")
        st.write(f"**检查模式:** {config['check_mode']}")

        if "results" in st.session_state and st.session_state.results:
            st.write(f"**总检查耗时:** {st.session_state.total_check_time:.2f}秒")
            st.write(f"**检查邮件数量:** {len(st.session_state.results)}")
            st.write(f"**总数据量:** {format_file_size(sum(r.get('body_size', 0) for r in st.session_state.results))}")

st.divider()
st.subheader("更新历史")
st.markdown("""

- **版本 1.9.0 (2025-11-06):**
  - ⏱️ 新增检查耗时统计功能，记录每封邮件的检查时间
  - 📊 新增邮件正文大小格式化显示 (B/KB/MB/GB)
  - ⚠️ 新增耗时异常检测，识别检查时间过长的邮件
  - 📈 新增耗时统计面板，显示总耗时、平均耗时和最长耗时
  - 🔍 优化异常检测逻辑，结合邮件大小和耗时综合判断
  - 🎨 在邮件详情中突出显示耗时异常项

- **版本 1.8.1 (2025-11-03):**
  - 🐛 修复run_check函数未定义错误，调整函数定义顺序
  - 🎨 重新设计界面布局，左侧简化配置，右侧功能丰富
  - 📦 新增批量下载功能，支持多选邮件打包下载
  - 🔄 优化分页体验，在结果列表底部也添加分页控件
  - ✅ 添加邮件选择功能，支持全选/取消全选
  - 📊 改进文件夹统计显示，操作流程更清晰

- **版本 1.7.4 (2025-11-03):**
  - 📈 彻底重构文件夹统计逻辑，确保包含所有邮件
  - 🔍 在获取文件夹列表时即进行完整的UID分析
  - 📊 新增详细的文件夹统计面板，显示序列号搜索 vs UID搜索差异
  - ⚠️ 实时检测并显示无效UID和计数差异问题
  - 🎯 解决与Foxmail等客户端的邮件数量差异问题

- **版本 1.7.3 (2025-11-03):**
  - 🔍 增强邮件搜索，使用多种搜索方式确保获取所有邮件
  - 📊 新增UID统计信息显示，区分普通搜索和UID搜索结果
  - ⚠️ 支持无效UID检测和单独展示
  - 📈 改进邮件计数准确性，解决与Foxmail的数量差异问题

- **版本 1.7.2 (2025-11-03):**
  - 🐛 修复下载功能，解决页面重置问题
  - 🔄 优化状态管理，保持检查结果持久化
  - 📥 改进邮件下载逻辑，支持重新连接
  - 🎨 优化界面布局，增强用户体验

- **版本 1.7.1 (2025-11-03):**
  - 🐛 修复IMAP响应解析问题，处理异常响应格式
  - 🔧 改进邮件获取逻辑，使用安全的fetch函数
  - ⚡ 移除并发检查，改为顺序检查避免连接冲突
  - 📧 优化邮件头解析和错误处理

- **版本 1.7.0 (2025-11-03):**
  - 🚀 新增三种检查模式：快速检查、完整检查、深度检查
  - ⚡ 使用并发处理大幅提升检查速度
  - 📊 增强文件夹信息显示（邮件数量和UID范围）
  - 💾 优化结果状态管理，避免页面刷新丢失数据
  - 🔍 新增结果筛选和分页功能
  - 📋 支持JSON格式导出

- **版本 1.6.1 (2025-08-25):**
  - 修复了获取文件列表时的`list index out of range`错误。

- **版本 1.6 (2025-08-25):**
  - 新增`获取完整邮件`按钮，可在获取到邮件检查列表后，点击下载eml格式邮件。

- **版本 1.5 (2025-08-25):**
  - 新增获取文件夹后的`下拉框`功能，可直接在文件夹列表下拉框内选择获取到的文件夹。

- **版本 1.4 (2025-08-15):**
  - 新增 `获取文件夹列表`按钮 ，可获取文件夹列表后再选择进行查询。

- **版本 1.3.1 (2025-08-15):**
  - 修改邮件序号框为自定义输入，取消了下拉框选择。

- **版本 1.3 (2025-08-15):**
  - 添加了更新历史部分，记录版本迭代内容。

- **版本 1.2 (2025-08-15):**
  - 添加了端口号选择下拉框，包含 143、993 和 587。
  - 修复了 `[SSL: WRONG_VERSION_NUMBER] wrong version number` 错误。

- **版本 1.1 (2025-08-15):**
  - 新增添加`Certfi`包的支持。
  - 创建了自定义SSL上下文来初始化`IMAP4_SSL`对象。

- **版本 1.0 (2025-08-14):**
  - 初始版本发布。

""", unsafe_allow_html=True)

st.divider()
st.subheader("说明")
st.markdown("""

   > 参考链接：[阿里邮箱IMAP场景示例](https://help.aliyun.com/document_detail/609361.html?spm=a2c4g.11186623.help-menu-35466.d_9_2_2_5.4c9b1d95SGlQGm&scm=20140722.H_609361._.OR_help-T_cn~zh-V_1)

   * 本网页工具由 `Deepseek-R1`、`Quark-AI编程`生成并持续进行版本迭代中 
   
""")

st.divider()
st.caption("© 2025 邮箱权限检查工具 | 版本 1.9.0 | 安全提示：您的邮箱凭据仅用于本次检查，不会被存储或传输到其他服务器")